<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="合同编号" prop="cmCode">
          <el-input
            v-model="queryParams.cmCode"
            placeholder="请输入合同编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="合同名称" prop="cmName">
          <el-input
            v-model="queryParams.cmName"
            placeholder="请输入合同名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="销售订单编号" prop="soId">
          <el-input
            v-model="queryParams.soId"
            placeholder="请输入销售订单编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="clientName">
          <el-input
            v-model="queryParams.clientName"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <!--        <el-form-item label="合同签订日期" prop="cmCreateDate">
                  <el-date-picker clearable
                                  v-model="queryParams.cmCreateDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择合同签订日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="合同额" prop="cmAmount">
                  <el-input
                    v-model="queryParams.cmAmount"
                    placeholder="请输入合同额"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="预计交货日期" prop="cmJiaoDate">
                  <el-date-picker clearable
                                  v-model="queryParams.cmJiaoDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择预计交货日期">
                  </el-date-picker>
                </el-form-item>-->

        <el-form-item label="合同状态" prop="cmState">
          <el-select
            v-model="queryParams.cmState"
            placeholder="合同状态"
            clearable
            style="width: 215px"
          >
            <el-option
              v-for="dict in dict.type.xscm_confirm_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['cm:xscm:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['cm:xscm:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['cm:xscm:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['cm:xscm:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="xscmList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="合同编号" align="center" prop="cmCode" width="200px">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleView(scope.row)"
            >{{ scope.row.cmCode }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="合同名称" align="center" prop="cmName"/>
        <el-table-column label="客户名称" align="center" prop="clientName" width="200"/>
        <el-table-column label="合同类型" align="center" prop="cmType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.contract_management_type" :value="scope.row.cmType"/>
          </template>
        </el-table-column>

        <el-table-column label="销售订单编号" align="center" prop="soId" width="150"/>
        <el-table-column label="合同签订日期" align="center" prop="cmCreateDate" width="100">
          <template slot-scope="scope">
            <el-tag type="success">{{ parseTime(scope.row.cmCreateDate, '{y}-{m}-{d}') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="合同额" align="center" prop="cmAmount">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.cmAmount">{{ formatCurrency(scope.row.cmAmount) }}</el-tag>
            <span v-else>{{ scope.row.cmAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预计交货日期" align="center" prop="cmJiaoDate">
          <template slot-scope="scope">
            <el-tag type="warning">{{ parseTime(scope.row.cmJiaoDate, '{y}-{m}-{d}') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="合同状态" align="center" prop="cmState">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.xscm_confirm_status" :value="scope.row.cmState"/>
          </template>
        </el-table-column>
        <!--        <el-table-column label="合同文件" align="center" prop="cmFileUrl"/>-->
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">

              <el-button
                size="mini"
                type="warning"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['cm:xscm:edit']"
                v-if="scope.row.cmState === 0"
              >修改
              </el-button>


              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['cm:xscm:remove']"
                v-if="scope.row.cmState === 0"
              >删除
              </el-button>


              <el-button
                size="mini"
                type="primary"
                icon="el-icon-document-checked"
                @click="handleConfirm(scope.row)"
                v-hasPermi="['cm:xscm:confirm']"
                v-if="scope.row.cmState === 0"
              >确认
              </el-button>

            <el-button
              size="mini"

              icon="el-icon-document-checked"
              @click="handleView(scope.row)"
              v-if="scope.row.cmState === 1"
            >详情
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改合同管理行对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="合同编号" prop="cmCode">
              <el-input v-model="form.cmCode" placeholder="请输入合同编号" :readonly="optType == 'view'"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                         active-color="#13ce66"
                         active-text="自动生成"
                         @change="handleAutoGenChange(autoGenFlag)"
                         v-if="optType !== 'view' ">
                >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="合同名称" prop="cmName">
              <el-input v-model="form.cmName" placeholder="请输入合同名称" :readonly="optType == 'view'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">

            <el-form-item label="客户编码" prop="clientCode">
              <el-input v-model="form.clientCode" placeholder="请输入客户编码" readonly>
                <el-button slot="append" @click="handleSelectClient" icon="el-icon-search"
                           v-if="optType != 'view'"></el-button>
              </el-input>
              <ClientSelect ref="clientSelect" @onSelected="onClientSelected"></ClientSelect>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="客户名称" prop="clientName">
              <el-input readonly v-model="form.clientName" placeholder="请输入客户名称"/>
            </el-form-item>
          </el-col>


        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户地址" prop="clientAddress">
              <el-input readonly v-model="form.clientAddress" placeholder="请输入客户地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="客户电话" prop="clientPhone">
              <el-input readonly v-model="form.clientPhone" placeholder="请输入客户电话"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="销售单编号" prop="soId">
              <el-input v-model="form.soId" placeholder="请选择销售订单编号" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectOrder"
                  icon="el-icon-search"
                  v-if="optType === 'add'">
                </el-button>
              </el-input>
              <OrderSelect ref="orderSelect" status="已生产" status2="已审批"
                           @onSelected="onOrderSelected"></OrderSelect>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="合同额" prop="cmAmount">
              <el-input v-model="form.cmAmount" placeholder="请输入合同额" :readonly="optType == 'view'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同签订日期" prop="cmCreateDate">
              <el-date-picker clearable
                              v-model="form.cmCreateDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择合同签订日期"
                              :disabled="optType == 'view'">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计交货日期" prop="cmJiaoDate">
              <el-date-picker clearable
                              v-model="form.cmJiaoDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择预计交货日期"
                              :disabled="optType == 'view'">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="合同文件" prop="cmFileUrl">
          <el-input v-model="form.cmFileUrl" type="textarea" placeholder="请输入内容" :readonly="optType == 'view'"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :readonly="optType == 'view'"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="optType !='view' " @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listXscm, getXscm, delXscm, addXscm, updateXscm, confirmXscm} from "@/api/mes/cm/xscm";
import {genCode} from "@/api/system/autocode/rule";
import ClientSelect from "@/components/clientSelect/single.vue";
import OrderSelect from "@/components/orderSelect/single.vue";
import {getOrder} from "@/api/mes/xs/order";

export default {
  name: "Xscm",
  dicts: ['xscm_confirm_status', 'contract_management_type'],
  components: {OrderSelect, ClientSelect},
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同管理行表格数据
      xscmList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,

        cmCode: null,
        cmName: null,
        soId: null,
        clientName: null,
        cmState: null,
      },
      // 表单参数
      form: {},
      optType: undefined,
      // 表单校验
      rules: {
        cmCode: [
          {required: true, message: "合同编号不能为空", trigger: "blur"}
        ], cmName: [
          {required: true, message: "合同名称不能为空", trigger: "blur"}
        ], clientId: [
          {required: true, message: "客户ID不能为空", trigger: "blur"}
        ], cmType: [
          {required: true, message: "合同类型0销售 1采购 2外协不能为空", trigger: "change"}
        ], soId: [
          {required: true, message: "销售订单编号不能为空", trigger: "blur"}
        ], cmCreateDate: [
          {required: true, message: "合同签订日期不能为空", trigger: "blur"}
        ], cmAmount: [
          {required: true, message: "合同额不能为空", trigger: "blur"}
        ], cmJiaoDate: [
          {required: true, message: "预计交货日期不能为空", trigger: "blur"}
        ], cmState: [
          {required: true, message: "合同状态   0草稿 1已确定不能为空", trigger: "blur"}
        ], cmFileUrl: [
          {required: true, message: "合同文件不能为空", trigger: "blur"}
        ], clientCode: [
          {required: true, message: "需要选择客户", trigger: "blur"}
        ],


      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleView(row) {
      this.reset();
      const lineId = row.lineId;

      getXscm(lineId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "销售合同详情";
        this.optType = "view";
      });
    },
    formatCurrency(number) {
      return new Intl.NumberFormat('zh-CN', {style: 'currency', currency: 'CNY'}).format(number);
    },
    handleSelectOrder() {
      this.$refs.orderSelect.showFlag = true;
    },
    handleSelectClient() {
      this.$refs.clientSelect.showFlag = true;
    },
    //客户选择弹出框
    onClientSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.clientId = obj.clientId;
        this.form.clientCode = obj.clientCode;
        this.form.clientName = obj.clientName;
        this.form.clientAddress = obj.address;
        this.form.clientPhone = obj.tel;
      }

    },
    //销售订单选择弹出框
    onOrderSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.soId = obj.soNumber;
      }
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('CM_XSCM_CODE').then(response => {
          this.form.cmCode = response;
        });
      } else {
        this.form.cmCode = null;
      }
    },
    /** 查询合同管理行列表 */
    getList() {
      this.loading = true;
      listXscm(this.queryParams).then(response => {
        this.xscmList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        clientName: null,
        clientAddress: null,
        clientPhone: null,
        lineId: null,
        cmCode: null,
        cmName: null,
        clientId: null,
        clientCode: null,
        soId: null,
        cmCreateDate: null,
        cmAmount: null,
        cmJiaoDate: null,
        cmState: null,
        cmFileUrl: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lineId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.optType = "add";
      this.open = true;
      this.title = "添加合同管理行";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(this.$store.state)
      this.reset();
      const lineId = row.lineId || this.ids
      getXscm(lineId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同管理行";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lineId != null) {
            updateXscm(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addXscm(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lineIds = row.cmCode || this.ids;
      this.$modal.confirm('是否确认删除合同管理行编号为"' + lineIds + '"的数据项？').then(function () {
        return delXscm(lineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleConfirm(row) {
      const lineIds = row.cmCode ;
      this.$modal.confirm('是否确认审批通过编号为"' + lineIds + '"的销售合同？ 审批通过后将不可撤回！？').then(function () {
        return confirmXscm(row.lineId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("确认审批通过！");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cm/xscm/export', {
        ...this.queryParams
      }, `xscm_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
